import {
	imageType
} from '@/utils/enum.js';
import {
	uploadFileToOSS
} from '@/utils/aliyOss.js';
import {
	useUserInfo
} from '@/stores/userInfo.js';
import dayjs from 'dayjs';

export const exUploadImages = (url, imageSize, type) => {
	return new Promise((resolve, reject) => {
		const userStore = useUserInfo();

		let imgType = url.substr(url.lastIndexOf('.') + 1);
		const isAllowed = imageType.includes(imgType);
		if (!isAllowed) {
			uni.$u.toast('只允许上传 JPG、PNG、SVG 、JPG格式图片！');
			return reject('格式不正确');
		}

		if (imageSize > 10485760) {
			uni.$u.toast('图片过大,请重新选择上传');
			return reject('图片过大');
		}

		let suffix = url.substr(url.lastIndexOf('.'));
		let newDateTime = Date.parse(new Date());
		let storageType = type === 0 ? 'upload' : 'avatar';

		let year = dayjs().year();
		let month = dayjs().month() + 1;
		let date = dayjs().date();
		let datetimeFormatStr = year + '-' + month + '-' + date;
		let bucketFilePath = null;

		if (storageType === 'avatar') {
			bucketFilePath = userStore.userData.wxopenid + storageType + newDateTime + 'head' + suffix;
		} else {
			const randomStr = Math.random().toString(36).substring(2, 8);
			bucketFilePath = userStore.userData.wxopenid + `/upload${datetimeFormatStr}/` + newDateTime + '_' + randomStr + suffix;
			//bucketFilePath = userStore.userData.wxopenid + `/upload${datetimeFormatStr}/` + newDateTime + suffix;
		}

		let ossUrl = 'https://sansanmedia-object-storage.oss-cn-beijing.aliyuncs.com';

		// 定义callback函数
		const callback = (err, data) => {
			if (err) {
				uni.$u.toast('上传失败');
				reject(err);
				return;
			}
			let link = ossUrl + '/' + bucketFilePath;
			uni.$u.toast('上传成功');
			resolve(link);
		};

		uploadFileToOSS(url, bucketFilePath, callback);
	});
};